package com.fit.pages.user;

import java.util.Date;

import org.apache.tapestry5.SelectModel;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.EnumSelectModel;

import com.fit.annotations.AdminAccess;
import com.fit.annotations.AnonymousAccess;
import com.fit.annotations.ProfessorAccess;
import com.fit.annotations.StudentAccess;
import com.fit.dao.user.UserDAO;
import com.fit.entities.user.User;
import com.fit.model.MD5;
import com.fit.model.Reg;
import com.fit.model.UserRole;
import com.fit.pages.ErrorPage;


@AdminAccess
@AnonymousAccess
@ProfessorAccess
@StudentAccess
public class AddAdmin {
	
	@Inject
	private Messages messages;

	 @Property
	 @SessionState(create = false)
	 private User user;
	 @Inject
	 private UserDAO userDAO;
	 @InjectPage
	 private ErrorPage errorPage;
	 @Property
	 @Persist
	 private boolean testStudent;
	 @Property
	 @Persist
	 private boolean testProff;
	 @Persist
	 @Property
	 private String error;
	 @Property
	 @Persist
	 private Reg user_reg;

	 @Persist
	 @Property
	 private String confirmation;


	 void onPrepare() {
	  user = new User();
	 }
	 
	 public SelectModel getUserReg() {
			return new EnumSelectModel(Reg.class, messages);
		}
	 

	 Object onSubmitFromCreateForm() {
		 if(user_reg==Reg.PROFESOR){
		  	   testProff = true;
		  	 testStudent = false;
		  	  	   }
		  	if(user_reg==Reg.STUDENT){
		 	  testStudent = true;
		 	 testProff = false;
		 	  	   }
	
			return null;
	  
	 }
	 private Class nextPage;
	 
		@OnEvent(value="selected", component="submitButton")
		void onSubmitButton()
		{
			 error="";
			  confirmation="";
			  	   if(user_reg==Reg.ADMIN){
			   user.setRole(UserRole.ADMIN);
			  	   }
			  	 if(user_reg==Reg.PROFESOR){
			  	   user.setRole(UserRole.PROFESSOR);
			  	  	   }
			  	if(user_reg==Reg.STUDENT){
			 	   user.setRole(UserRole.STUDENT);
			 	  	   }
			
			   user.setPassword(MD5.md5(user.getPassword()));
			   userDAO.save(user);
			   confirmation = "User successfully added";
			   nextPage =  Browse.class;
		}
	 
	 @OnEvent(component = "ResetConfLink")
	 Object onResetConfLink() {
	  confirmation="";
	  return null;
	 }
	 
	 @OnEvent(component = "ResetErrorLink")
	 Object onResetErrorLink() {
	  error="";
	  return null;
	 }
	 
	 
	 
	}